package com.hyf.gateway.filter;

import com.hyf.gateway.constants.CommonConstants;
import com.hyf.gateway.util.EncodeUtils;
import org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

/**
 * @author baB_hyf
 * @date 2021/07/12
 */
@Component
public class RioGatewayHttpHeadersFilter implements HttpHeadersFilter {

    @Override
    public HttpHeaders filter(HttpHeaders headers, ServerWebExchange exchange) {

        String paasId = CommonConstants.PASS_ID;
        String paasToken = CommonConstants.TOKEN;
        String uid = CommonConstants.USER_ID;
        long now = System.currentTimeMillis();
        String uinfo = "unused";
        String ext = "unused";

        String timestamp = Long.toString((long) Math.floor(now / 1000));
        String nonce = Long.toHexString(now) + "-" + Long.toHexString((long)
                Math.floor(Math.random() * 0xFFFFFF));
        String sign_date = String.format("%s%s%s,%s,%s,%s%s", timestamp, paasToken, nonce, uid, uinfo, ext, timestamp);
        String signature = EncodeUtils.sha256(sign_date);

        // headers.add("x-tif-paasid", paasId);
        headers.add("x-tif-timestamp", timestamp);
        headers.add("x-tif-nonce", nonce);
        headers.add("x-tif-uid", uid);
        headers.add("x-tif-uinfo", uinfo);
        headers.add("x-tif-ext", ext);
        headers.add("x-tif-signature", signature);

        return headers;
    }
}
